import {Component, OnInit, ViewChild} from '@angular/core';
import {Compartment, EditorState} from "@codemirror/state";
import {basicSetup, EditorView} from "@codemirror/basic-setup";
import {HighlightStyle, tags} from "@codemirror/highlight";
import {keymap} from "@codemirror/view";
import {selectAll} from "@codemirror/commands";
import {sql} from "@codemirror/lang-sql";
import {BarnSqlService} from "../service/barn-sql.service";
import {ActivatedRoute} from "@angular/router";
import {BarnSql} from "../entity/barn-sql";
import {BarnProject} from "../../project/entity/barn-project";
import {ProductService} from "../../product/service/product.service";
import {Clipboard} from "@angular/cdk/clipboard";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-sql-preview',
  templateUrl: './sql-preview.component.html',
  styleUrls: ['./sql-preview.component.less']
})
export class SqlPreviewComponent implements OnInit {

  sql: BarnSql = new BarnSql()
  projects: BarnProject[] = []

  @ViewChild('editor', {static: true})
  holder
  view: EditorView

  loading = false

  constructor(private barnSqlService: BarnSqlService, private routeInfo: ActivatedRoute, private productService: ProductService,
              private clipboard: Clipboard, private message: NzMessageService) {
  }

  ngOnInit(): void {
    this.initSqlEditor()
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    if (pid) {
      this.loading = true
      this.barnSqlService.getById(pid).subscribe(value => {
        if (value) {
          this.sql = value
          const t = this.view.state.update({changes: {insert: value.sqlText, from: 0}});
          this.projects = value.use
          this.view.dispatch(t);
          if (this.sql.productId) {
            this.productService.getById(this.sql.productId).subscribe(product => {
              this.sql.productName = product.productName
              this.loading = false
            }, () => this.loading = false);
          } else {
            this.loading = false
          }
        }
      }, () => this.loading = true);
    }
  }

  copySql() {
    const result = this.clipboard.copy(this.sql.sqlText)
    if (result) {
      this.message.info("复制成功!")
    } else {
      this.message.error("复制失败!")
    }
  }

  /**
   * 初始化编辑器
   */
  initSqlEditor() {
    const language = new Compartment()
    const tabSize = new Compartment()

    // 设置编辑器样式
    const myTheme = EditorView.theme({
      '&': {
        backgroundColor: '#fff'
      },
      '&.cm-editor': {
        height: 'calc(100vh - 370px)',
        width: 'calc(100vw - 490px)'
      }
    }, {dark: false})

    // 设置高亮样式
    const myHighlightStyle = HighlightStyle.define([
      {tag: tags.keyword, color: '#f1a703', fontWeight: 'border'},
      {tag: tags.quote, color: '#f1a703', fontWeight: 'border'},
      {tag: tags.comment, color: '#f5d', fontStyle: 'italic'}
    ])

    // 设置编辑器的基本属性
    const state = EditorState.create({
      extensions: [
        basicSetup,
        keymap.of([{key: "Ctrl-a", run: selectAll}]),
        language.of(sql()),
        EditorView.editable.of(false),
        tabSize.of(EditorState.tabSize.of(4)),
        myTheme,
        myHighlightStyle
      ]
    })

    // 初始化
    this.view = new EditorView({
      state,
      parent: this.holder.nativeElement
    })
  }
}
